from flask_restplus import Resource, Namespace, fields, marshal_with
from common.utils.decorators import login_required
from flask import g, request, jsonify
from app.models import db
from app import redis_clent, app
from app.models.hello import Hello
from flask_restplus import reqparse, inputs
from app.routes.hello.schemas import hello_mds, post_hello_mds, TestSchemas
from app.tasks.test import test
from .marshmallow import UpdateFiles


hello_ns = Namespace("hello")
# hello_ns.schema_model(name=Hello, schema="hello")

hello_md = hello_mds(hello_ns)
hello_md_post = post_hello_mds(hello_ns, hello_md)


class HelloWord(Resource):

    hello_md = hello_mds(hello_ns)
    hello_md_post = post_hello_mds(hello_ns, hello_md)
    # method_decorators = {"get": [login_required]} # 检查用户登录的装饰器
    @marshal_with(hello_md)  # 指定序列化返回
    @hello_ns.doc(params={"name": "a name"})  # 指定输入字段
    def get(self):
        data = request.args

        # 延时任务apply_async
        result = test.apply_async(countdown=10)
        # 取出要执行任务的时间对象，调用apply_async方法，args是任务函数传的参数，eta是执行的时间
        # v1 = datetime(2019, 7, 12, 21, 48, 12)
        # 将v1时间转成utc时间
        # v2 = datetime.utcfromtimestamp(v1.timestamp())
        # result1 = add1.apply_async(args=[3, 8], eta=v2)

        return data

    @hello_ns.expect(hello_md, validate=True)
    @hello_ns.marshal_with(hello_md_post)
    def post(self):
        json = request.json
        # data = hello_ns.payload
        data = []
        print(json.get("name"))
        data.append({"name": json.get("name")})
        return {"total": json.get("total"), "data": data}


class FileUpdate(Resource):

    test_schemas = TestSchemas(hello_ns)

    @hello_ns.expect(test_schemas.file_update_query(), validate=False)
    @hello_ns.marshal_with(test_schemas.file_update_body())
    def post(self):
        # 上传多张文件
        # print(request.files.listvalues())
        for i in request.files.lists():

            # print(dict(i))
            file_list = UpdateFiles().load(data={"file": i[1], "name": "yanziliang"})
            print(file_list)
